<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>管理员</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <el-row :gutter="10">
        <el-col :span="4">
          <el-input v-model="queryInfo.query" placeholder="请输入内容" clearable @clear="getAdminList">
            <el-button slot="append" icon="el-icon-search" @click="getAdminList" ></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="AdminList"
        border
        style="width: 100%">
        <el-table-column prop="id" label="id" width="50"> </el-table-column>
        <el-table-column prop="username" label="用户名" width="180"> </el-table-column>
        <el-table-column prop="nickname" label="昵称" width="180"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="loginip" label="登录ip"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini"  @click="showEditDialog(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeAdminById(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        :hide-on-single-page="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加用户 -->
    <el-dialog title="添加管理员" :visible.sync="addDialogVisible" width="30%" @close="addDialogClosed">
      <!-- 内容主体 -->
      <el-form
        :model="addAdminForm"
        ref="addAdminFormRef"
        :rules="addAdminFormRules"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addAdminForm.username"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="addAdminForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addAdminForm.password"></el-input>
        </el-form-item>
        <el-form-item label="权限组" prop="group_id">
          <template>
            <el-select v-model="addAdminForm.group_id" placeholder="请选择" >
              <el-option
                v-for="item in groupList"
                :key="item.id"
                :label="item.title"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addAdminForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addAdminForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAdmin">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户 -->
    <el-dialog title="编辑管理员" :visible.sync="editDialogVisible" width="30%" @close="editDialogClosed">
      <!-- 内容主体 -->
      <el-form
        :model="editAdminForm"
        ref="editAdminFormRef"
        :rules="editAdminFormRules"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username" >
          <el-input v-model="editAdminForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="editAdminForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="权限组" prop="group_id">
          <template>
            <el-select v-model="editAdminForm.group_id" placeholder="请选择" >
              <el-option
                v-for="item in groupList"
                :key="item.id"
                :label="item.title"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editAdminForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editAdminForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAdmin">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义邮箱规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        // 合法邮箱
        return callback()
      }
      callback(new Error('请输入合法邮箱'))
    }
    // 自定义手机号规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      // 返回一个错误提示
      callback(new Error('请输入合法的手机号码'))
    }
    return {
      queryInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      AdminList: [],
      total: 0,
      groupList: [],
      // 添加用户对话框
      addDialogVisible: false,
      // 用户添加
      addAdminForm: {
        username: '',
        nickname: '',
        password: '',
        group_id: '',
        email: '',
        mobile: ''
      },
      // 用户添加表单验证规则
      addAdminFormRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 10,
            message: '用户名的长度在2～10个字',
            trigger: 'blur'
          }
        ],
        nickname: [
          {
            required: true,
            message: '请输入昵称',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 10,
            message: '用户名的长度在2～10个字',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入用户密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 18,
            message: '用户密码的长度在6～18个字',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号码',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      },
      // 添加用户对话框
      editDialogVisible: false,
      getAdmin: {
        id: ''
      },
      // 编辑添加
      editAdminForm: {},
      editAdminFormRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 10,
            message: '用户名的长度在2～10个字',
            trigger: 'blur'
          }
        ],
        nickname: [
          {
            required: true,
            message: '请输入昵称',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 10,
            message: '用户名的长度在2～10个字',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号码',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getAdminList()
  },
  methods: {
    // 获取管理员列表
    async getAdminList () {
      const { data: res } = await this.$http.get(this.GLOBAL.adminList, {
        params: this.queryInfo
      })
      if (res.status !== 200) return this.$message.error(res.info)
      this.AdminList = res.data.AdminList
      this.total = res.data.total
      this.groupList = res.data.groupList
    },
    // 每页条数改变时
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getAdminList()
    },
    // 当前页
    handleCurrentChange (pagenum) {
      this.queryInfo.pagenum = pagenum
      this.getAdminList()
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed () {
      this.$refs.addAdminFormRef.resetFields()
    },
    // 添加用户
    addAdmin () {
      // 提交请求前，表单预验证
      this.$refs.addAdminFormRef.validate(async valid => {
        // console.log(valid)
        // 表单预校验失败
        if (!valid) return
        const { data: res } = await this.$http.post(this.GLOBAL.addAdmin, this.addAdminForm)
        if (res.status !== 200) {
          return this.$message.error(res.info)
        }
        this.$message.success(res.info)
        // 隐藏添加用户对话框
        this.addDialogVisible = false
        this.getAdminList()
      })
    },
    // 关闭编辑框
    editDialogClosed () {
      this.$refs.editAdminFormRef.resetFields()
    },
    // 显示编辑框
    async showEditDialog (id) {
      // 请求获取数据
      this.getAdmin.id = id
      const { data: res } = await this.$http.get(this.GLOBAL.getAdmin, {
        params: this.getAdmin
      })
      if (res.status !== 200) {
        return this.$message.error(res.info)
      }
      this.editAdminForm = res.data.adminInfo
      this.getAdmin.id = ''
      this.editDialogVisible = true
    },
    // 保存编辑信息
    saveAdmin () {
      this.$refs.editAdminFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(this.GLOBAL.saveAdmin, this.editAdminForm)
        if (res.status !== 200) {
          return this.$message.error(res.info)
        }
        this.$message.success(res.info)
        // 隐藏添加用户对话框
        this.editDialogVisible = false
        this.getAdminList()
      })
    },
    // 删除管理员
    async removeAdminById (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该管理员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {})
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.get(this.GLOBAL.delAdmin, {
        params: { id: id }
      })
      if (res.status !== 200) {
        return this.$message.error(res.info)
      }
      this.$message.success(res.info)
      this.getAdminList()
    }
  }

}
</script>

<style lang="less" scoped>
.el-select{
  width: 100%;
}
</style>
